package com.uni.controller;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;
import com.uni.common.entity.User;
import com.uni.common.util.PageBean;
import com.uni.service.impl.UserServiceImpl;
import com.uni.util.ReturnData;

@Controller
@RequestMapping("user")
public class UserController {
	
	@Autowired
	private UserServiceImpl userService;
	
	@RequestMapping("findList")
	@ResponseBody
	public ReturnData findList(PageBean<User> pageBean,HttpServletRequest request){
		ReturnData rd = new ReturnData();
		Map<String , Object> param = Maps.newHashMap();
		String phone = request.getParameter("phone");
		String nickname = request.getParameter("nickname");
		if(StringUtils.isNotEmpty(phone)){
			param.put("phone", phone);
		}
		if(StringUtils.isNotEmpty(nickname)){
			param.put("nickname", nickname);
		}
		pageBean.setParam(param);
		List<User> userList = userService.findList(pageBean);
		if(userList!=null&&userList.size()>0){
			pageBean.setContent(userList);
			pageBean.setTotalCount(userService.countList(pageBean));
			return rd.okBack(pageBean);
		}
		return rd.okBack();
	}
	
	/**
	 * 查找用户信息
	 * @param userId
	 * @return
	 */
	@RequestMapping("findById")
	@ResponseBody
	public ReturnData findById(Long userId){
		ReturnData rd = new ReturnData();
		if(userId==null){
			return rd.failBack("userId不能为空");
		}
		User user = userService.findById(userId);
		if(user==null){
			return rd.failBack("用户不存在");
		}
		return rd.okBack(user);
	}
	
	/**
	 * 修改用户信息
	 * @param userId
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public ReturnData update(User user){
		ReturnData rd = new ReturnData();
		int ret = userService.update(user);
		if(ret>0){
			return rd.okBack(user);
		}
		return rd.failBack("修改失败");
	}
	
	/**
	 * 删除用户
	 * @param userId
	 * @return
	 */
	@RequestMapping("del")
	@ResponseBody
	public ReturnData del(String ids){
		ReturnData rd = new ReturnData();
		String[] a = ids.split(",");
		int ret = userService.del(a);
		if(ret>0){
			return rd.okBack("删除成功");
		}
		return rd.failBack("删除失败");
	}
}
